<template>
  <div class="flex flex-col h-full">
    <div class="flex flex-col flex-1" v-if="isInteractionEnabled">
      <!-- 聊天消息区域 -->
      <div
        class="chat-box flex-1 overflow-y-auto pt-3 border-gray-300"
        ref="chatBoxRef"
        v-if="!playerStore.isKeyboardVisible"
      >
        <div
          v-for="(message, index) in _messages"
          :key="index"
          class="chat-message mb-2"
          v-if="imStore.messages.length > 0"
        >
          <span
            class="rounded-full px-2 py-1 shadow-sm flex items-center gap-2 bg-white"
          >
            <!-- 头像 -->
            <img
              v-if="message.avatar"
              :src="message.avatar"
              alt="avatar"
              class="w-6 h-6 rounded-full object-cover"
            />
            <span class="username font-bold text-blue-600">
              {{ message.username }}
              <span class="text-xs text-gray-400 ml-1">({{ message.id }})</span
              >：
            </span>
            <span class="content text-gray-800">
              {{ message.content }}
            </span>
          </span>
        </div>
      </div>

      <!-- 输入框 -->
      <div
        class="chat-input mt-4 flex items-center gap-2 rounded-xl pl-2"
        :class="
          !playerStore.isKeyboardVisible
            ? 'fixed bottom-0 left-0 w-full p-2 bg-opacity-50 text-white z-20'
            : ''
        "
      >
        <input
          v-model="newMessage"
          type="text"
          placeholder="说点什么吧..."
          class="flex-grow px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400 text-black"
          @keyup.enter="sendMessage"
        />
        <button
          @click="sendMessage"
          class="flex-shrink-0 px-4 py-2 rounded-lg bg-pink-500 text-white hover:bg-pink-600 transition"
        >
          发送
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useTencentIM } from "@/utils/tencent-im";
import { ref, onUnmounted, onMounted, watch, nextTick, computed } from "vue";
import { usePlayerStore } from "@/store/usePlayer";
import { useKeyboard } from "@/store/useKeyboard";

const imStore = useTencentIM();
const playerStore = usePlayerStore();
const chatBoxRef = ref<HTMLElement | null>(null);
const messageHeight = 40;
const visibleCount = ref(5);
useKeyboard(
  () => {
    playerStore.setKeyboardVisible(true);
    window.scrollTo(0, 0);
  },
  () => {
    playerStore.setKeyboardVisible(false);
  }
);

defineProps({
  isInteractionEnabled: {
    type: Boolean,
    default: true
  }
});

interface Message {
  username: string;
  id: string;
  avatar: string;
  content: string;
}

const updateVisibleCount = () => {
  if (chatBoxRef.value) {
    const height = chatBoxRef.value.clientHeight;
    visibleCount.value = Math.max(1, Math.floor(height / messageHeight));
  }
};

onMounted(() => {
  // updateVisibleCount();
  // window.addEventListener("resize", updateVisibleCount);
});

// watch(chatBoxRef, updateVisibleCount);

const _messages = computed<Message[]>(() =>
  imStore.messages.map(msg => ({
    username: msg.nick,
    id: msg.from,
    avatar: msg.avatar,
    content: msg.payload.text
  }))
);

const newMessage = ref<string>("");

const sendMessage = (): void => {
  if (newMessage.value.trim() !== "") {
    imStore.sendMessageToGroup(newMessage.value.trim());
    newMessage.value = "";
  }
};
const scrollToBottom = () => {
  if (chatBoxRef.value) {
    chatBoxRef.value.lastElementChild?.scrollIntoView({
      behavior: "smooth",
      block: "end"
    });
  }
};
watch(_messages, () => {
  nextTick(() => {
    scrollToBottom();
  });
});
onUnmounted(() => {
  window.removeEventListener("resize", updateVisibleCount);
});
</script>

<style scoped>
input::placeholder {
  color: #a0aec0;
}
</style>
